<template>
  <div class="app-container">
    <el-form :inline="true" class="search-wrap">
      <el-form-item label="关键词">
        <el-input v-model="q.keywords" placeholder="关键词" @keyup.enter.native="load" />
      </el-form-item>
      <el-form-item label="注册方式">
        <enum-selector v-model="q.register_types" :enums="registerTypeList" :multiple="true" placeholder="全部"></enum-selector>
      </el-form-item>
      <!--  <el-form-item label="激活状态">
            <el-select v-model="q.isActive" placeholder="激活状态">
              <el-option v-for="item in ativeList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
            <el-form-item label="邮箱验证状态">
              <el-select v-model="q.emailConfirmed" placeholder="邮箱验证状态">
                <el-option v-for="item in confirmedList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="手机验证状态">
              <el-select v-model="q.phoneNumberConfirmed" placeholder="手机验证状态">
                <el-option v-for="item in confirmedList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          <el-form-item label="注册时间">
              <el-date-picker v-model="creationTime" :picker-options="pickerOptions" :editable="false" unlink-panels type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
            </el-form-item> -->
      <el-form-item>
        <el-button type="warning" icon="el-icon-search" @click="load">搜索</el-button>
        <el-button type="default" icon="el-icon-refresh" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="filter-container">
      <el-button v-permission="['identity.add_user']" class="filter-item" type="primary" icon="el-icon-plus" @click="addData()">添加</el-button>
      <el-button v-permission="['identity.view_user']" class="filter-item" type="primary" icon="el-icon-upload2" @click="importData()">导入
      </el-button>
      <el-button v-permission="['identity.view_user']" class="filter-item" type="primary" icon="el-icon-download" @click="exportData()">导出
      </el-button>

      <el-dropdown class="filter-item" :hide-on-click="false">
        <el-button :disabled="itemsChecked.length === 0">
          批量操作<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <span v-permission="['identity.delete_user']" @click="batchDeleteData()"><i class="el-icon-delete"></i>删除</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <el-table :key="tableKey" v-loading="tableLoading" :data="items" border fit highlight-current-row style="width: 100%;" @sort-change="sortChange" @selection-change="selectionChange">
      <el-table-column type="selection" width="45" align="center"></el-table-column>
      <el-table-column :label="'头像'" width="80" align="center">
        <template slot-scope="scope">
          <router-link :to="'/user/'+scope.row.id">
            <el-avatar v-if="scope.row.avatar" :src="scope.row.avatar" :alt="scope.row.username" :title="'点击查看详情'" :size="22" shape="square" />
            <el-avatar v-if="!scope.row.avatar" icon="el-icon-s-custom" :alt="scope.row.username" :title="'点击查看详情'" :size="22" shape="square" />
          </router-link>
        </template>
      </el-table-column>
      <el-table-column :label="'用户名'" min-width="150" align="center">
        <template slot-scope="scope">
          <!-- <router-link :to="'/user/'+scope.row.id">
            <el-link type="primary" :title="'点击查看详情'" :underline="false">{{ scope.row.username }}</el-link>
          </router-link> -->
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'昵称'" min-width="150" align="center">
        <template slot-scope="scope">
          <!-- <router-link :to="'/user/'+scope.row.id">
            <el-link type="primary" :title="'点击查看详情'" :underline="false">{{ scope.row.nickname }}</el-link>
          </router-link> -->
          <span>{{ scope.row.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'手机号码'" width="120" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.phone_number ? scope.row.phone_number:"无" }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'邮箱'" width="200" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.email ? scope.row.email:"无" }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'创建时间'" prop="date_joined" sortable="custom" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.date_joined | formatDateTime('YYYY-MM-DD HH:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'最后登录时间'" prop="last_login" sortable="custom" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.last_login | formatDateTime('YYYY-MM-DD HH:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'注册方式'" prop="register_type" width="130" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.register_type | enumLabel(registerTypeList) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="120" align="center" fixed="right">
        <template slot-scope="{ row }">
          <el-button v-permission="['identity.change_user']" type="text" @click="editData(row.id)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-dropdown :hide-on-click="false">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <span v-permission="['identity.add_user']" @click="changePassword(row.id)">修改密码</span>
              </el-dropdown-item>
              <!-- <el-dropdown-item>
                <span v-permission="['identity.change_user']" @click="setRoles(row.id)">设置角色</span>
              </el-dropdown-item>
              <el-dropdown-item>
                <span v-permission="['identity.add_user','identity.change_user']" @click="changePermissions(row)">更改权限</span>
              </el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="totalCount > 0" :total="totalCount" :skip-count.sync="q.offset" :max-result-count.sync="q.limit" @pagination="getList" />

    <edit-user-dialog ref="editUserDialog" @save="load()"></edit-user-dialog>
    <change-password-dialog ref="changePasswordDialog"></change-password-dialog>
    <set-roles-dialog ref="setRolesDialog"></set-roles-dialog>
    <change-permissions-dialog ref="changePermissionsDialog"></change-permissions-dialog>
    <import-users-dialog ref="importDataDialog" @save="load()"></import-users-dialog>
  </div>
</template>

<script>
import _ from "lodash";
import { pickerOptions } from "@/utils/helpers/datetime-picker-helper";
import { confirmedList, registerTypeList } from "@/utils/enums.js";
import Pagination from "@/components/ApePagination";
import EnumSelector from "@/components/ApeSelectors/enum-selector";
import ChangePermissionsDialog from "./components/ChangePermissionsDialog";
import EditUserDialog from "./components/EditUserDialog";
import ChangePasswordDialog from "./components/ChangePasswordDialog";
import SetRolesDialog from "./components/SetRolesDialog";
import ImportUsersDialog from "./components/ImportUsersDialog";

import { getUserPagedList, deleteUser, exportUser } from "@/api/identity/user";

export default {
  name: "UserList",
  components: {
    Pagination,
    EnumSelector,
    ChangePermissionsDialog,
    EditUserDialog,
    SetRolesDialog,
    ChangePasswordDialog,
    ImportUsersDialog
  },
  data() {
    return {
      pickerOptions,
      confirmedList: [{ label: "全部", value: undefined }, ...confirmedList],
      registerTypeList,
      creationTime: [],
      q: {
        keywords: undefined,
        register_types: [],
        creation_time_start: undefined,
        creation_time_end: undefined,
        sorting: "id",
        offset: 0,
        limit: 10
      },
      totalCount: 0,
      items: [],
      itemsChecked: [],
      tableLoading: true,
      tableKey: 0
    };
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      this.q.offset = 0;
      this.q.creation_time_start = this.creationTime[0];
      this.q.creation_time_end = this.creationTime[1];
      this.getList();
    },
    resetSearch() {
      this.creationTime = [];
      this.q = {
        keywords: undefined,
        register_types: [],
        creation_time_start: undefined,
        creation_time_end: undefined,
        sorting: "id",
        offset: 0,
        limit: 10
      };
      this.load();
    },
    getList() {
      this.tableLoading = true;
      getUserPagedList(this.q).then(result => {
        this.items = result.items;
        this.totalCount = result.total_count;
        this.tableLoading = false;
      });
    },
    sortChange(sortData) {
      const { prop, order } = sortData;
      if (prop && order === "descending") {
        this.q.sorting = prop + " desc";
      } else if (prop && order === "ascending") {
        this.q.sorting = prop;
      } else {
        this.q.sorting = "id";
      }
      this.load();
    },
    selectionChange(selection) {
      this.itemsChecked = selection;
    },
    addData() {
      this.editData();
    },
    editData(id) {
      this.$refs["editUserDialog"].show(id);
    },
    batchDeleteData() {
      const selectedIds = this.itemsChecked.map(item => item.id);
      if (selectedIds.length <= 0) {
        this.$message({ message: "至少选中一条记录", type: "warning" });
        return;
      }
      this.$confirm("删除后不可恢复， 是否继续?", "确定删除选中的用户吗？", { type: "warning" })
        .then(() => {
          for (let i = 0; i < selectedIds.length; i++) {
            const id = selectedIds[i];
            deleteUser(id).then(() => {
              if (i + 1 === selectedIds.length) {
                this.load();
                this.$message({ message: "删除成功", type: "success" });
              }
            });
          }
        })
        .catch(() => { });
    },
    changePassword(id) {
      this.$refs["changePasswordDialog"].show(id);
    },
    setRoles(id) {
      this.$refs["setRolesDialog"].show(id);
    },
    changePermissions(user) {
      this.$refs["changePermissionsDialog"].show(user);
    },
    activeUsers(isActive) {
      const selectedIds = this.itemsChecked.map(item => _.parseInt(item.id));
      if (selectedIds.length <= 0) {
        this.$message({ message: "至少选中一条记录", type: "warning" });
        return;
      }
      console.log("isActive", isActive);
    },
    importData() {
      this.$refs["importDataDialog"].show();
    },
    exportData() {
      exportUser().then(result => {
        const blob = new Blob([result], {
          type:
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        });
        const objectUrl = URL.createObjectURL(blob);
        const a = document.createElement("a");
        document.body.appendChild(a);
        a.setAttribute("style", "display:none");
        a.setAttribute("href", objectUrl);
        const fileName = "用户列表.xlsx";
        a.setAttribute("download", fileName);
        a.click();
        URL.revokeObjectURL(objectUrl);
      });
    }
  }
};
</script>

<style scope>
.user-item {
  margin-top: 10px;
}
</style>

